package com.wf.smartcomm.server.admin.action;

import javax.annotation.Resource;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdScheduler;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.ContextLoaderListener;

import com.opensymphony.xwork2.ModelDriven;
import com.wf.smartcomm.server.bean.User;
import com.wf.smartcomm.server.bean.Village;
import com.wf.smartcomm.server.job.QuartzJobFactory;
import com.wf.smartcomm.server.job.ScheduleJob;
import com.wf.smartcomm.server.service.ScheduleService;
import com.wf.smartcomm.server.service.VillageService;
import com.wf.smartcomm.server.util.ConstantUtils;
import com.wf.smartcomm.server.util.StringUtil;

@Controller("adminVillageAction")
@Scope("prototype")
public class VillageAction extends BaseAction implements ModelDriven<Village>{

	private Village village = new Village();
	
	@Resource
	private VillageService villageServiceImpl;
	
	@Resource
	private ScheduleService scheduleService;
	
	public void save() throws Exception{
		if (!StringUtil.isEmpty(village.getObjectId())) {
			villageServiceImpl.update(village);
		} else {
			villageServiceImpl.save(village);
			ScheduleJob job = new ScheduleJob();
			job.setJobId(village.getObjectId());
			job.setJobName(ConstantUtils.JOB_BILL_CREATE);
			job.setCronExpression("0 0 2 * * ?");
			scheduleService.add(job);
			Scheduler scheduler = (Scheduler) ContextLoaderListener.getCurrentWebApplicationContext().getBean("schedulerFactoryBean");
			JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class)
					.withIdentity(job.getJobId(), job.getJobName()).build();
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
			CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobId(), job.getJobName())
					.withSchedule(scheduleBuilder).build();
			try {
				scheduler.scheduleJob(jobDetail, trigger);
				if (!scheduler.isStarted()) {
					scheduler.start();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		printJsonData(200);
	}
	
	public String edit() throws Exception{
		village = villageServiceImpl.get(village.getObjectId());
		request.setAttribute("village", village);
		return "edit";
	}
	
	public void detail() throws Exception{
		village = villageServiceImpl.get(village.getObjectId());
		User user = (User) session.getAttribute("loginUser");
		user.setLoginVillage(village);
		//session.setAttribute("loginUser", user);
		printJsonData(200);
	}
	
	@Override
	public Village getModel() {
		// TODO Auto-generated method stub
		return village;
	}

}
